# encoding: utf-8

class Admin::HistoriesController < Admin::ApplicationController
  layout 'admin'

  def index
    @tasks = current_user.tasks.no_filter.day(nil, params[:date] || Time.now.strftime("%Y-%m-%d") )#(current_user._id)
    @today = Time.now
  end

  def show
    if @task = current_user.tasks.where(:_id=> params[:id]).first
      @all_tweets_count = @task.all_tweets(:location => params[:location], :time => params[:time]).count
      @tweets = @task.all_tweets(:page => (params[:page]||1), :location => params[:location], :time => params[:time] ).present_json(:history)
    else
      redirect_to '/histories'
    end
  end

  def destroy_tweets
    tweets = []
    params[:tweets].each_value{|_t| tweets << _t['_id']}
    Utility::BasicTweet.destroy_comment_batch(tweets)
    render_msg :type => :success, :msg => "删除成功"
  end

  def destroy
    if task = Task.where(:_id=> params[:id]).first
      unless task.is_filter
        task.filtered each do |_task|
          del_task _task
        end
      end
      del_task task
    end
  end

  def clear_task
    rtype = nil
    msg   = ""
    unless task = current_user.tasks.where(:_id => params[:task]).first
      rtype, msg = :error, "根本没有这个任务啊 (╯‵□′)╯︵┻━┻"
    end
    case params[:actn].to_s
    when 'unclicked'
      task.clear_unclicked
      rtype, msg = :success, "清除成功!"
    when 'all'
      if task.all_tweets(:all => true).count > 0
        rtype, msg = :error, "已经发送过评论了,不能直接删除任务 (╯‵□′)╯︵┻━┻"
      else
        task.push_histories.destroy_all
        task.master_task.filtered_tasks.destroy_all
        task.destroy
        rtype, msg = :success, "清除成功"
      end
    when 'failed'
      task.clear_failed
      rtype, msg = :success, "清除成功!"
    else
      rtype, msg = :error, "参数错误了吧 (╯‵□′)╯︵┻━┻"
    end
      render_msg :type => rtype, :msg => msg
  end

  def del_task(task)
    task.push_histories.each do |ph|
      if params[:del_tweets]
        ph.tweets.destroy_all
        ph.destroy
      else
        ph.task = task.master_task
        ph.save
      end
    end
    task.destroy
  end

  def get_comments
    render_json do
      if st = Statistics::Tweet.where(:_id => params[:tid]).first
        comments = st.get_comments((rand(7) > 4) ? true : false)
      end
    end
  end

  def add_comment
    render_json do
      if st = Statistics::Tweet.where(:_id => params[:tid]).first
        comments = st.add_comment(params[:comment])
      end
    end
  end

end